﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Timers;
using MCorder.Control;

namespace MCorder2022
{
    public partial class MCorderForm : Form
    {
        public MCorderForm()
        {
            InitializeComponent();
        }
        private MCorderControl MC_Control = new MCorderControl();//Mcorder.Control
        System.Timers.Timer daqTimer = new System.Timers.Timer();//电流位置速度取值定时器

        List<float> position_xlist = new List<float>();
        List<float> current_ylist = new List<float>();//XY轴list

        //窗体初始化操作
        private void MCorderForm_Load(object sender, EventArgs e)
        {
            toolStripStatusLabel2.Alignment = ToolStripItemAlignment.Right;//版权声明靠右

            readconfig();//读取配置文件只1次
            while (MC_Control.Init())//初始化,连接采集卡、翠欧控制器
            {
                daqTimer.Interval = 150; //这个时间单位毫秒,比如10秒，就写10000 
                daqTimer.Elapsed += new ElapsedEventHandler(daqTimer_Elapsed);
                daqTimer.Start();//打开定时器
                timer1.Start();//数值图像刷新，长度测量判断
                return;
            }
        }

        double current_read, position_read, speed_read;//电流、位置、速度变量
        int DrawCount;
        void daqTimer_Elapsed(object sender, ElapsedEventArgs e)//从Control读取数据-定时器
        {
            if (MC_Control.Cur_list.Count() > 0 && MC_Control.Pos_list.Count() > 0)//若电流位置都有数值
            {
                int min_ad = MC_Control.Cur_list.Count();//电流值数量
                int min_pos = MC_Control.Pos_list.Count();//位置值数量
                int min = min_pos < min_ad ? min_pos : min_ad;//取数量最小值

                for (int i = 0; i < min; i++)
                {
                    current_read = MC_Control.Cur_list[i];
                    position_read = MC_Control.Pos_list[i];
                    if (drawCueve)//是否画图
                    {
                        if (DrawCount < 10)//前10个点不画图
                        {
                            DrawCount++;
                        }
                        else
                        {
                            if (MC_Control.Pos_list[i] > 0 && MC_Control.Cur_list[i] != 0)//位置值电流值都不为零时，向XY轴list添加数据（图像出现过电流突然为零情况）
                            {
                                current_ylist.Add((float)MC_Control.Cur_list[i]);
                                position_xlist.Add((float)MC_Control.Pos_list[i]);
                            }
                        }
                    }
                }
                MC_Control.Cur_list.Clear();
                MC_Control.Pos_list.Clear();//取完数值清空Control-list
            }
            if (MC_Control.Speed_list.Count > 0)//速度有数值
            {
                speed_read = MC_Control.Speed_list[0];
                MC_Control.Speed_list.Clear();//取数清空
            }
        }
        private void timer1_Tick(object sender, EventArgs e)//200ms
        {
            if (iCount % 5 == 0)//5次timer运行一次，1Hz刷新
            {
                if (current_ylist.Count() > 0 && position_xlist.Count() > 0)//XY轴有数
                {
                    zGraph.f_Refresh();//刷新图像
                }
                label_pos.Text = position_read.ToString("0.000");
                label_cur.Text = current_read.ToString("0.000");//右上方数值显示

                Tips_Cur.Text = " Current;" + current_read.ToString("0.000");
                Tips_pos.Text = "Position;" + position_read.ToString("0.000");
                Tips_speed.Text = "Speed;" + speed_read.ToString("0.000");//左下方数值显示
                if (Dir == 1)
                    Tips_direction.Text = "Direction:L";
                if (Dir == 0)
                    Tips_direction.Text = "Direction:R";
                Distance_Check();//长度测量检测是否到达长度
            }
            iCount++;
        }
        private void Distance_Check()
        {
            if (checkBox_distanceLimit.Checked)//是否开启长度测量
            {
                double stop_pos = (double)numericUpDown_stopposition.Value;//设定测量长度
                if (Convert.ToDouble(label_pos.Text) > stop_pos)//长度超过设定长度
                {
                    MC_Control.StopRoll();
                    MC_Control.StopDataSaving();//停止保存
                    timer1.Stop();//关闭刷新界面

                    if (MessageBox.Show("已到达预设长度", "提示") == DialogResult.Yes)
                    {
                        MC_Control.Cur_list.Clear();
                        MC_Control.Pos_list.Clear();//control list清空
                        button_Start.Text = "开始";

                        button_Open.Enabled = true;
                        button_TorqueOK.Enabled = true;
                        button_Torque.Enabled = true;
                        button_Coff.Enabled = true;
                    }
                    else
                    {
                        MC_Control.Cur_list.Clear();
                        MC_Control.Pos_list.Clear();
                        button_Start.Text = "开始";

                        button_Open.Enabled = true;
                        button_Torque.Enabled = true;
                        button_Coff.Enabled = true;
                    }
                }
            }
        }
        private void readconfig()
        {
            if (File.Exists("config.ini"))
            {
                string[] readconfig = File.ReadAllLines("config.ini");

                for (int ijk = 0; ijk < readconfig.Length; ijk++)
                {
                    string[] linebreak = readconfig[ijk].Split('=');
                    if (linebreak.Length > 1)
                    {
                        if (linebreak[0].Contains("distace_lim"))
                        {
                            checkBox_distanceLimit.Checked = (linebreak[1].Trim() == "true" ? true : false);
                        }
                        else if (linebreak[0].Contains("stop_distace"))
                        {
                            numericUpDown_stopposition.Value = Convert.ToDecimal(linebreak[1].Trim());
                        }
                        else if (linebreak[0].Contains("speed"))
                        {
                            numericUpDown_speed.Value = Convert.ToDecimal(linebreak[1].Trim());
                        }
                        else if (linebreak[0].Contains("direction"))
                        {
                            button_direction.ImageIndex = Convert.ToInt32(linebreak[1].Trim());
                        }
                        else if (linebreak[0].Contains("ivindex"))
                        {
                            textbox_Coff.Text = linebreak[1].Trim();
                            current_coefficient = (float)Convert.ToDouble(textbox_Coff.Text);
                        }
                        else if (linebreak[0].Contains("torque"))
                        {
                            textbox_Torque.Text = linebreak[1].Trim();
                            tension = Convert.ToDouble(textbox_Torque.Text);
                        }
                    }
                }
            }
        }
        private void setconfig()
        {
            string writeconfig = "";
            writeconfig += "distace_lim = " + (checkBox_distanceLimit.Checked ? "true" : "false") + Environment.NewLine;
            writeconfig += "stop_distace = " + numericUpDown_stopposition.Value.ToString() + Environment.NewLine;
            writeconfig += "speed = " + numericUpDown_speed.Value.ToString() + Environment.NewLine;
            writeconfig += "direction = " + button_direction.ImageIndex.ToString() + Environment.NewLine;
            writeconfig += "ivindex = " + textbox_Coff.Text + Environment.NewLine;
            writeconfig += "torque = " + textbox_Torque.Text;
            System.IO.File.WriteAllText("config.ini", writeconfig);
        }

        private long iCount = 0;//用于刷新界面

        double ad_base = 0;

        string backup_file_path = "";

        private void numericUpDown_speed_ValueChanged_1(object sender, EventArgs e)
        {
            Tips_speed.Text = "速度：" + numericUpDown_speed.Value.ToString("F2");
        }

        //-----------------------------------------------------------------------------
        private void Init()
        {
            position_xlist.Clear();
            current_ylist.Clear();
            ad_base = 0;
            drawCueve = true;
            SetPar();//参数设置

            zGraph.f_reXY();
            zGraph.f_ClearAllPix();
            zGraph.f_LoadOnePix(ref position_xlist, ref current_ylist, Color.Red, 1);
            zGraph.f_AddPix(ref position_xlist, ref current_ylist, Color.Red, 1);
            zGraph.f_Refresh();
        }
        public int clockwise = 0, Dir = 0;
        public double speed = 0;
        string fileName1 = "";
        private void SetPar()
        {
            setdirection();
            speed = (double)numericUpDown_speed.Value;
            speed = speed / 3600;
            tension = Convert.ToDouble(textbox_Torque.Text);
            fileName1 = textBox1.Text;
            MC_Control.setCoff(current_coefficient);
        }

        private bool followlasttime = false;
        bool OpenfromExtern = false;

        private void button_Start_Click(object sender, EventArgs e)
        {
            if (button_Start.Text == "开始")
            {
                button_Torque.Enabled = false;
                button_Open.Enabled = false;
                button_Coff.Enabled = false;
                followlasttime = false;
                if (position_xlist.Count() > 10)
                {
                    if (MessageBox.Show("是否继续上次测量？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        followlasttime = true;
                    }
                    else
                    {
                        followlasttime = false;
                    }
                }

                drawCueve = true;

                setconfig();
                DrawCount = 0;


                SetPar();
                if (followlasttime == false)
                {
                    Init();
                    MC_Control.Cur_list.Clear();
                    MC_Control.Pos_list.Clear();

                }
                if (timer1.Enabled == false)
                {
                    timer1.Start();
                }

                MC_Control.StartRoll_Plane(fileName1, Dir, speed, tension, followlasttime, OpenfromExtern, ad_base, position_xlist, current_ylist, backup_file_path);
                OpenfromExtern = false;
                button_Start.Text = "停止";
            }
            else if (button_Start.Text == "停止")
            {
                button_Coff.Enabled = true;
                button_Open.Enabled = true;
                button_Torque.Enabled = true;

                DrawCount = 0;
                drawCueve = false;
                MC_Control.StopRoll();
                MC_Control.StopDataSaving();
                button_Start.Text = "开始";
            }
        }

        private void MCorderForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void MCorderForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            daqTimer.Enabled = false;
            timer1.Enabled = false;
            MC_Control.StopRoll();
            MC_Control.StopDataSaving();
            MC_Control.StopComm();
        }

        bool drawCueve;
        private void button_Catalogue_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(Environment.CurrentDirectory + "\\data\\");
        }

        private void button_Open_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "打开文件";
            ofd.Filter = "文本文档(*.txt)|*.txt";
            ofd.Multiselect = false;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                if (ofd.CheckFileExists)
                {
                    backup_file_path = ofd.FileName;
                    string[] a = System.IO.File.ReadAllLines(ofd.FileName);
                    int j = a.Length - 1;

                    ad_base = 0;

                    OpenfromExtern = true;

                    zGraph.f_ClearAllPix();
                    zGraph.f_reXY();
                    position_xlist.Clear();
                    current_ylist.Clear();

                    for (int i = 0; i < j - 1; i++)
                    {
                        if (a[i].Contains("Coefficient(V/A):"))
                        {
                            try
                            {
                                current_coefficient = (float)Convert.ToDouble(a[i].Replace("Coefficient(V/A):", "").Trim());
                            }
                            catch (Exception)
                            {

                            }
                        }
                        else if (a[i].Contains("Base Current(A):"))
                        {
                            try
                            {
                                ad_base = (float)Convert.ToDouble(a[i].Replace("Base Current(A):", "").Trim());
                            }
                            catch (Exception)
                            {

                            }
                        }
                        else
                        {
                            try
                            {
                                string[] b = a[i].Split('\t');
                                if (b.Length == 4)
                                {
                                    position_xlist.Add(float.Parse(b[1]));
                                    current_ylist.Add(float.Parse(b[2]));
                                }
                            }
                            catch (Exception)
                            { }
                        }
                    }
                    zGraph.f_LoadOnePix(ref position_xlist, ref current_ylist, Color.Red, 1);
                    zGraph.f_Refresh();
                    Tips_coff.Text = current_coefficient.ToString();
                }
            }
        }

        string souceFile;
        private void button_SaveAs_Click(object sender, EventArgs e)
        {
            try
            {
                souceFile = MC_Control.OtherFileName();
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Title = "保存文件";
                sfd.Filter = "文本文档(*.txt)|*.txt";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    File.Copy(souceFile, sfd.FileName, true);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        double tension = 0.0;
        private void button_TorqueOK_Click(object sender, EventArgs e)
        {
            tension = Convert.ToDouble(textbox_Torque.Text);
            if (tension > 12) tension = 12;
            if (tension < 0) tension = 0;
        }

        float current_coefficient = 0;//1个电流系数
        private void button_CoffOK_Click(object sender, EventArgs e)
        {
            current_coefficient = (float)Convert.ToDouble(textbox_Coff.Text);
            Tips_coff.Text = "IV系数：" + current_coefficient.ToString();
        }

        private void button_direction_Click(object sender, EventArgs e)
        {
            button_direction.ImageIndex = 1 - button_direction.ImageIndex;
            setdirection();
        }

        private void setdirection()
        {
            if (button_direction.ImageIndex == 0) { Dir = 0; }
            else { Dir = 1; }
        }
    }
}
